package org.petstore.persistence.impl;

import org.petstore.domain.Category;
import org.petstore.persistence.CategoryDAO;
import org.petstore.persistence.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 * extends JdbcDaoSupport
 * 配置文件bean.xml没成功
 * import org.springframework.jdbc.core.support.JdbcDaoSupport;
 */
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class CategoryDAOImpl implements CategoryDAO {
    /**
     * 用于和数据库交互的,实现对表的CURD操作
     * 适合单表操作
     * 可以用BeanPropertyRowMapper
     * public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException
     * public <T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException
     */
    private final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    private static final String GET_CATEGORY_LIST = " SELECT CATID AS categoryId, NAME, DESCN AS description FROM CATEGORY";
    private static final String GET_CATEGORY_BY_ID = " SELECT CATID AS categoryId, NAME, DESCN AS description FROM CATEGORY WHERE CATID = ?";

    public CategoryDAOImpl() {
    }

    /**
     * description 获取所有大类
     *
     * @return List<Category>
     * @author huangzhangyan
     * @date 2021/10/31 18:29
     */
    @Override
    public List<Category> getCategoryList() {
        List<Category> list;
        list = template.query(GET_CATEGORY_LIST, new CategoryRowMapper());
        //CategoryRowMapper自己写的
        //也可以用new BeanPropertyRowMapper<>(Category.class)
        return list;
    }

    /**
     * description 根据ID获取大类
     *
     * @param categoryId:
     * @return Category
     * @author huangzhangyan
     * @date 2021/10/31 18:32
     */
    @Override
    public Category getCategory(String categoryId) {
        Category category;
        try {
            category = template.queryForObject(GET_CATEGORY_BY_ID, new BeanPropertyRowMapper<>(Category.class), categoryId);
        } catch (DataAccessException e) {
            category = null;
        }
        return category;
    }
}

/**
 * BeanPropertyRowMapper 可以不用自己写Mapper
 * Java字节码 .class
 * getBean
 */

class CategoryRowMapper implements RowMapper<Category> {

    /**
     * description 把结果集数据封装到Category中,然后spring把每个Account加到集合中
     *
     * @param resultSet:
     * @param i:
     * @return Object
     * @author huangzhangyan
     * @date 2021/11/4 1:16
     */
    @Override
    public Category mapRow(ResultSet resultSet, int i) throws SQLException {
        Category category = new Category();
        category.setCategoryId(resultSet.getString("categoryId"));
        category.setName(resultSet.getString("name"));
        category.setDescription(resultSet.getString("description"));
        return null;
    }
}
